<template>
    <div>
        <el-form :model="model" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm page-form">
            <el-row>

                <el-col :span="8">
                    <el-form-item label="入库编号" prop="Number">
                        <el-input v-model="model.Number" placeholder="请输入库编号"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="状态" prop="Status">
                        <el-select v-model="model.Status">
                            <el-option label="待审核" value="0"></el-option>
                            <el-option label="已审核" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="经办人" prop="RealName">
                            <el-input v-model="model.RealName" placeholder="请输入经办人"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

             <el-row>

                <el-col :span="8">
                    <el-form-item label="入库仓" prop="WareHouseId">
                         <el-select v-model="model.WareHouseName" placeholder="请选择入库仓" style="width: 100%;" @change="wareHouseChange">
                            <el-option v-for="item in WarehouseList" :key="item.Id" :label="item.WarehouseName" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="入库类型" prop="WareHouseMode">
                        <el-select v-model="model.WareHouseMode" placeholder="请选择入库类型" allow-create filterable>
                            <el-option label="借入" value="借入"></el-option>
                            <el-option label="受赠" value="受赠"></el-option>
                            <el-option label="代销" value="代销"></el-option>
                            <el-option label="其他" value="其他"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="入库日期" prop="WarehouseDate">
                        <el-date-picker type="datetime" placeholder="选择入库日期" v-model="model.WarehouseDate" ></el-date-picker>
                    </el-form-item>
                </el-col>
                
                <el-col :span="8">
                    <el-form-item label="备注" prop="Remark">
                        <el-input v-model="model.Remark"></el-input>
                    </el-form-item>
                </el-col>

            </el-row>
            
            <div class="page-tool">
                <el-button type="primary" plain icon="el-icon-plus" @click="addBom" size="small">新增</el-button>
                <el-button  type="danger" plain icon="el-icon-delete" size="small" @click="delBom">删除</el-button>
            </div>

            <el-table :data="tableData" ref="dataForm" v-loading="isLoading" height="360" show-summary :summary-method="getSummaries">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column  prop="ItemCode" label="编号" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="ItemName" label="名称" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="Spec" label="规格" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="UnitOfMeasure" label="单位" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="CurrCount" label="库存" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="Amount" label="金额" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="TaxPrice" label="含税单价" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="TaxAmount" label="含税金额" :show-overflow-tooltip="true"></el-table-column>

                <el-table-column prop="Count" label="数量" :show-overflow-tooltip="true">
                     <template slot-scope="scope">
                        <el-input v-model="scope.row.Count" @change="handleTaxChange(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="Price" label="商品单价" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.Price" @change="handleTaxChange(scope.row)"></el-input>
                        </template>
                    </el-table-column>
                 <el-table-column prop="Tax" label="税率" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.Tax" @change="handleTaxChange(scope.row)"></el-input>
                        </template>
                </el-table-column>
                <el-table-column prop="Remark" label="备注" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.Remark" />
                    </template>
                </el-table-column>

                <el-table-column label="操作" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-button type="text" @click="del(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

             <div class="page-form-action">
                <el-button type="primary" @click="submitForm">{{ isUpdate ? '立即保存' : '立即创建' }}</el-button>
                <el-button @click="resetForm">重置</el-button>
            </div>

             <!-- 弹窗 -->
            <el-dialog append-to-body :close-on-click-modal="false" :title="dialogDomain.title"
                :visible.sync="dialogDomain.dialogVisible" width="60%">
                       <SelectedItemFourStock @callback="AddBomCallBack"  :ItemList="tableData" :WareHouseId="this.model.WareHouseId.toString()"
                v-if="dialogDomain.dialogVisible " />
            </el-dialog>  

        </el-form>
    </div>
</template>

<script>
import SelectedItemFourStock from '@/views/Product/ProductView/components/SelectedItemFourStock.vue';

export default {
    components:{
        SelectedItemFourStock
    },
    props:{
        model:{
            require: true,
            type: Object,
        },
        isUpdate: {
            require: true,
            type: Boolean
        }
    },
    data(){
        return{
            WarehouseList:[],
            tableData:[],
            isLoading: false,

            pageDomain:{
                PageIndex:1,
                PageSize:10,
                TotalCount:0,
            },

            dialogDomain:{
                title:'添加产品',
                dialogVisible:false,
            },

        rules:{
            Number: { required: true, message: '请输入入库编号', trigger: 'blur' },
            RealName: { required: true, message: '请输入经办人', trigger: 'blur' },
            WareHouseId: { required: true, message: '请选择入库仓' },
            WareHouseMode: { required: true, message: '请选择入库类型', trigger: 'blur' },
            WarehouseDate: { required: true, message: '请选择入库日期', trigger: 'blur' },
        }
        }
    },
    created(){
         //获取仓库数据调用方法
        this.getWareHouseData();

        if(this.isUpdate){
            this.GetOtherWareHouseItemById()
        }
    },
    methods:{
            wareHouseChange(model){
                this.model.WareHouseId=model.Id;
                this.model.WareHouseName=model.WarehouseName;
                console.log(this.model)
            },

            getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总价';
                    return;
                }
                if (column.property === 'Amount' ||column.property === 'TaxPrice' ||column.property === 'TaxAmount' || column.property === 'Price') {
                    const values = data.map(item => Number(item[column.property]));
                    

                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                                
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += ' 元';
                    } else {
                        sums[index] = '';
                    }
                }
                else {
                    sums[index] = '';
                }
                
            });
            return sums;
        },
        handleTaxChange(row){
             if(row.Tax>1){
                row.Tax=1;
                this.showNotify('税率应为0~1之间（0.13=13%）');
            }
            if(row.Tax>0){
                row.TaxPrice = (row.Price * (1 + Number(row.Tax))).toFixed(2); // 含税单价
                row.TaxAmount = (row.TaxPrice * row.Count).toFixed(2); // 含税金额
            }
            else{
                row.TaxPrice = row.Price; // 含税单价
                row.TaxAmount = (row.TaxPrice * row.Count).toFixed(2);
            }

            row.Amount = (row.Count * row.Price).toFixed(2);//金额
            
        },

        addBom(){
            if (this.model.WareHouseId == '' || this.model.WareHouseId==undefined) {
                this.showNotify('请选择入库仓');
                return;
            }
            this.dialogDomain.title = "选择商品";
            this.dialogDomain.dialogVisible = true;
        },

        delBom(){
            if(this.$refs.dataForm.selection.length<=0)
            {
                this.showNotify('请选择一项');
                return;
            }
            this.$refs.dataForm.selection.forEach(row=>{
                const index=this.tableData.indexOf(row);
                this.tableData.splice(index,1);
            });
        },

        del(model){
            let index=this.tableData.indexOf(model);
            this.tableData.splice(index,1);
        },
        submitForm(){
            this.$refs['ruleForm'].validate((valid)=>{
                if(valid){
                    if(this.isUpdate){
                        this.put();
                    }
                    else{
                        this.add();
                    }
                }
                else{
                    this.showNotify('请输入必填项');
                    return false;
                }
            });
        },
        resetForm(){
            this.$refs['ruleForm'].resetFields();
        },
        add() {
            console.log(this.model)  
            this.$http.postForm('/api/OtherWareHouse', { model: this.model,OtherWareHouseItemString:JSON.stringify(this.tableData) }, { loading: this.$loading() })
            .then(res => {
                this.$emit('callback');
                console.log(res);
            })

        },
         put() {
            console.log(this.tableData);
            this.$http.putForm('/api/OtherWareHouse', { model: this.model,OtherWareHouseItemString:JSON.stringify(this.tableData) }, { loading: this.$loading() })
            .then((res) => {
                this.$emit('callback');
                console.log(res);
            })
        },
        GetOtherWareHouseItemById(){
            this.isLoading=true;
            this.$http.get('/api/OtherWareHouse/GetOtherWareHouseItemById',{
                params:{
                    OtherWareHouseId:this.model.Id,
                    WareHouseId:this.model.WareHouseId
                }
            })
            .then(res=>{
                console.log(res)
                this.isLoading=false;
                this.tableData = res.Data;
            })
        },
        getWareHouseData() {
             this.$http.get('/api/Warehouse/GetAll')
                .then(res => {
                    this.WarehouseList=res.Data;
                })
        },
        AddBomCallBack(){
            this.dialogDomain.dialogVisible=false;
            let arr = [];
            this.tableData.map(x=>{
                var obj=new Object();
                this.$set(obj, 'ItemCode', x.ItemCode);
                this.$set(obj, 'ItemId', x.ItemId);
                this.$set(obj, 'ItemName', x.ItemName);
                this.$set(obj, 'Spec', x.Spec);
                this.$set(obj, 'UnitOfMeasure', x.UnitOfMeasure);
                this.$set(obj, 'CurrCount', x.CurrCount);
                this.$set(obj, 'Amount', x.Amount|| x.SalePrice  );
                this.$set(obj, 'TaxAmount', x.TaxAmount|| 0);
                this.$set(obj, 'TaxPrice', x.TaxPrice|| 0);
                this.$set(obj, 'Count', x.Count || 1);
                this.$set(obj, 'Price', x.Price ||x.SalePrice);
                this.$set(obj, 'Tax', x.Tax || 0);
                this.$set(obj, 'Remark', x.Remark);
                arr.push(obj);
            })
            this.tableData=arr;
        }
    }
}
</script>

<style>

</style>